<template>
  <div class="fish-distribution-container">
    <div class="table-operations">
      <a-button type="primary" @click="showAddModal">
        <template #icon><plus-outlined /></template>
        添加分布区域
      </a-button>
      <a-input-search
        v-model:value="searchText"
        placeholder="搜索区域名称"
        style="width: 250px; margin-left: 16px"
        @search="onSearch"
      />
    </div>

    <a-table
      :columns="columns"
      :data-source="filteredDistributions"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'fishSpeciesList'">
          <a-space>
            <a-tag v-for="species in record.fishSpeciesList" :key="species">
              {{ species }}
            </a-tag>
          </a-space>
        </template>
        <template v-if="column.key === 'waterType'">
          <a-tag :color="record.waterType === '海水' ? 'blue' : 'green'">
            {{ record.waterType }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showEditModal(record)"><EditOutlined /> 编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条记录吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteDistribution(record.id)"
            >
              <a-button type="primary" danger><DeleteOutlined /> 删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑分布区域模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      :confirmLoading="confirmLoading"
    >
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="区域名称" name="region">
          <a-input v-model:value="formState.region" placeholder="请输入区域名称" />
        </a-form-item>
        <a-form-item label="鱼类种类" name="fishSpecies">
          <a-select
            v-model:value="formState.fishSpecies"
            mode="multiple"
            placeholder="请选择鱼类种类"
            style="width: 100%"
          >
            <a-select-option v-for="fish in fishOptions" :key="fish">{{ fish }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="水域类型" name="waterType">
          <a-select v-model:value="formState.waterType" placeholder="请选择水域类型">
            <a-select-option value="淡水">淡水</a-select-option>
            <a-select-option value="海水">海水</a-select-option>
            <a-select-option value="半咸水">半咸水</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="水温范围" name="temperature">
          <a-input v-model:value="formState.temperature" placeholder="例如: 18-24°C" />
        </a-form-item>
        <a-form-item label="水深范围" name="depth">
          <a-input v-model:value="formState.depth" placeholder="例如: 50-200米" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useFishDistributionStore } from '@/stores/fishDistributionStore';

const distributionStore = useFishDistributionStore();
const loading = computed(() => distributionStore.loading);
const distributions = computed(() => distributionStore.distributions);

const searchText = ref('');
const modalVisible = ref(false);
const modalTitle = ref('添加分布区域');
const confirmLoading = ref(false);
const isEdit = ref(false);
const currentId = ref(null);
const formRef = ref(null);

const fishOptions = [
  '鲤鱼', '草鱼', '鲫鱼', '鲢鱼', '鲶鱼', '黄鱼', '带鱼', '金枪鱼', 
  '鲈鱼', '鲨鱼', '沙丁鱼', '三文鱼', '白鱼', '鳕鱼', '鲳鱼'
];

const formState = reactive({
  region: '',
  fishSpecies: [],
  waterType: '',
  temperature: '',
  depth: ''
});

const rules = {
  region: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
  fishSpecies: [{ required: true, message: '请选择至少一种鱼类', trigger: 'change', type: 'array' }],
  waterType: [{ required: true, message: '请选择水域类型', trigger: 'change' }],
  temperature: [{ required: true, message: '请输入水温范围', trigger: 'blur' }],
  depth: [{ required: true, message: '请输入水深范围', trigger: 'blur' }]
};

const columns = [
  {
    title: '区域名称',
    dataIndex: 'region',
    key: 'region',
    sorter: (a, b) => a.region.localeCompare(b.region)
  },
  {
    title: '鱼类种类',
    dataIndex: 'fishSpeciesList',
    key: 'fishSpeciesList',
    customRender: ({ text }) => {
      if (Array.isArray(text)) {
        return text.join('、');
      }
      return text;
    }
  },
  {
    title: '水域类型',
    dataIndex: 'waterType',
    key: 'waterType',
    filters: [
      { text: '淡水', value: '淡水' },
      { text: '海水', value: '海水' },
      { text: '半咸水', value: '半咸水' }
    ],
    onFilter: (value, record) => record.waterType === value
  },
  {
    title: '水温范围',
    dataIndex: 'temperature',
    key: 'temperature'
  },
  {
    title: '水深范围',
    dataIndex: 'depth',
    key: 'depth'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
];

const filteredDistributions = computed(() => {
  if (!searchText.value) {
    return distributions.value;
  }
  return distributions.value.filter(item => 
    item.region.toLowerCase().includes(searchText.value.toLowerCase())
  );
});

const resetForm = () => {
  formState.region = '';
  formState.fishSpecies = [];
  formState.fishSpeciesList = [];
  formState.waterType = '';
  formState.temperature = '';
  formState.depth = '';
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const showAddModal = () => {
  resetForm();
  isEdit.value = false;
  modalTitle.value = '添加分布区域';
  modalVisible.value = true;
};

const showEditModal = (record) => {
  isEdit.value = true;
  currentId.value = record.id;
  modalTitle.value = '编辑分布区域';
  
  formState.region = record.region;
  formState.fishSpecies = record.fishSpeciesList || [];
  formState.waterType = record.waterType;
  formState.temperature = record.temperature;
  formState.depth = record.depth;
  
  modalVisible.value = true;
};

const handleModalOk = () => {
  formRef.value.validate().then(async () => {
    confirmLoading.value = true;
    
    try {
      // 准备提交的数据
      const submitData = {
        ...formState,
        // 将数组转换为字符串
        fishSpecies: formState.fishSpecies.join('/')
      };

      if (isEdit.value) {
        await distributionStore.updateDistribution(currentId.value, submitData);
        message.success('分布区域信息更新成功');
        await distributionStore.fetchDistributions();
      } else {
        await distributionStore.addDistribution(submitData);
        message.success('分布区域添加成功');
        await distributionStore.fetchDistributions();
      }
      
      modalVisible.value = false;
      resetForm();
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      confirmLoading.value = false;
    }
  }).catch(error => {
    console.log('表单验证失败:', error);
  });
};

const deleteDistribution = async (id) => {
  try {
    await distributionStore.deleteDistribution(id);
    message.success('分布区域删除成功');
    await distributionStore.fetchDistributions();
  } catch (error) {
    message.error('删除失败: ' + error.message);
  }
};

const onSearch = () => {
  // 搜索功能已通过计算属性实现
};

onMounted(() => {
  distributionStore.fetchDistributions();
});
</script>

<style scoped>
.fish-distribution-container {
  padding: 0 10px;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style> 